<?

class Sales extends CI_Controller {

	public function __construct()
	{
		parent::__construct();

		if(!$this->auth->is_admin() && !$this->auth->is_super_admin())
			$this->auth->verify();

		$this->load->library('cart');
		$this->load->model('item_model');
		$this->load->model('sales_model');
	}

	public function index()
	{
		$data['page'] = 'admin/sales';
		$this->load->view('admin/index', $data);
	}

	public function sales_table_update()
	{
		$this->load->view('admin/includes/_sales_summary');
	}

	public function add_item_cart($id)
	{
		$item = $this->item_model->search_items_by_id($id)->row();
		$data = array(
			'id' => $item->item_id,
			'qty' => 1,
			'price' => $item->item_retail_price,
			'name' => $item->item_name,
			'inventory' => $item->item_quantity,
			'disc' => 0);
		$this->cart->insert($data);
	}

	public function update_item_cart($rowid, $field, $value)
	{
		$data = array('rowid'=>$rowid, $field=>$value);
		$this->cart->update_all($data);
	}

	public function cancel_sale()
	{
		$this->cart->destroy();
	}

	public function complete_sale()
	{
		$sale_id = sha1(rand());
		foreach($this->cart->contents() as $item){
			$item_total = ($item['price'] - (($item['price']*$item['disc'])/100))*$item['qty'];
			$item_discount_price = (($item['price']*$item['disc'])/100)*$item['qty'];
			$each_item = array(
				'sale_id' => $sale_id,
				'item_id' => $item['id'],
				'sale_item_quantity' => $item['qty'],
				'sale_item_discount' => $item['disc'],
				'sale_item_discount_price' => $item_discount_price,
				'sale_item_total' => $item_total
			);
			$this->sales_model->save_sale_items($each_item);
		}
		$sale_total = $this->sales_model->get_sale_total_item_by_sale_id($sale_id)->row('sale_item_total');

		$sale_info = array(
			'sale_id' => $sale_id,
			'sale_total' => $sale_total,
			'sale_comment' => $this->input->post('comment')
		);
		$this->sales_model->save_sale($sale_info);

		$get_item = $this->item_model->get_item_by_id($item['id']);
		$this->item_model->update_item(array('item_quantity'=>$get_item->item_quantity-$item['qty']), $item['id']);

		$this->cart->destroy();
		echo 'sales complete';
	}
}